package com.ndphu.comic.gui.fragment.readnow;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.ndphu.comic.R;
import com.ndphu.comic.gui.activity.MainActivity;
import com.ndphu.comic.gui.fragment.searchbook.AbstractSearchBookFragment;
import com.ndphu.comic.gui.list.model.SearchBookItem;
import com.ndphu.comic.io.Utils;
import com.ndphu.comic.io.extend.AsyncTask;

public class RecentBooksFragment extends AbstractSearchBookFragment implements OnItemClickListener {
	private GridView mGridView;
	private GridViewAdapter mGridViewAdatper;
	private SharedPreferences mRecentBooksPref;
	private SharedPreferences mImageCachePref;
	private static Map<String, Bitmap> mCachedBitmaps = new HashMap<String, Bitmap>();
	private List<String> mLoading = new ArrayList<String>();

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_recent_read, container, false);
		mGridView = (GridView) view.findViewById(R.id.fragment_read_now_grid_view);
		mGridViewAdatper = new GridViewAdapter(getActivity(), 0);
		mGridView.setAdapter(mGridViewAdatper);
		mGridView.setOnItemClickListener(this);
		return view;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		mRecentBooksPref = getActivity().getSharedPreferences(MainActivity.PREF_RECENT_BOOKS, Context.MODE_APPEND);
		mImageCachePref = getActivity().getSharedPreferences(MainActivity.PREF_IMAGE_CACHE, Context.MODE_APPEND);
		/*String recentBooks = mRecentBooksPref.getString(MainActivity.PREF_RECENT_BOOKS_LIST, "");
		if (recentBooks.length() > 0) {
			// Load recent books
			try {
				JSONArray array = new JSONArray(recentBooks);
				for (int i = array.length() - 1; i >= 0; --i) {
					JSONObject object = array.getJSONObject(i);
					mGridViewAdatper.add(getItemFromJSONObject(object));
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}*/
	}

	private SearchBookItem getItemFromJSONObject(JSONObject object) {
		String bookName = getPropertyFromJSONObject(object, MainActivity.EXTRA_BOOK_NAME);
		String bookDesc = getPropertyFromJSONObject(object, MainActivity.EXTRA_BOOK_DESC);
		String bookUrl = getPropertyFromJSONObject(object, MainActivity.EXTRA_BOOK_URL);
		String bookCoverUrl = getPropertyFromJSONObject(object, MainActivity.EXTRA_BOOK_COVER_URL);
		String bookSource = getPropertyFromJSONObject(object, MainActivity.EXTRA_BOOK_SOURCE);

		SearchBookItem item = new SearchBookItem(bookName, bookDesc, bookUrl, bookCoverUrl, bookSource);
		return item;
	}

	private String getPropertyFromJSONObject(JSONObject object, String property) {
		try {
			return object.getString(property);
		} catch (JSONException ex) {

		}
		return null;
	}

	public class GridViewAdapter extends ArrayAdapter<SearchBookItem> {

		private LayoutInflater mInflater;
		private Bitmap mWaiting;

		public GridViewAdapter(Context context, int textViewResourceId) {
			super(context, textViewResourceId);
			mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			mWaiting = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null || convertView.getTag() == null || !(convertView.getTag() instanceof ViewHolder)) {
				convertView = mInflater.inflate(R.layout.gridview_searchbook_item, parent, false);
				ViewHolder holder = new ViewHolder();
				holder.cover = (ImageView) convertView.findViewById(R.id.listitem_search_book_item_cover);
				holder.bookName = (TextView) convertView.findViewById(R.id.listitem_search_book_item_book_name);
				holder.bookUrl = (TextView) convertView.findViewById(R.id.listitem_search_book_item_desc);
				convertView.setTag(holder);
			}
			ViewHolder holder = (ViewHolder) convertView.getTag();
			SearchBookItem item = getItem(position);
			fillDataToItem(holder, item);
			return convertView;
		}

		private void fillDataToItem(ViewHolder holder, SearchBookItem item) {
			holder.bookName.setText(item.bookName);
			Bitmap bitmap = getImageFromUrl(item.bookCoverLink);
			holder.cover.setImageBitmap(bitmap);
			holder.bookUrl.setText(item.bookLink);
		}

		private Bitmap getImageFromUrl(final String imageUrl) {
			synchronized (mCachedBitmaps) {
				if (mCachedBitmaps.containsKey(imageUrl)) {
					return mCachedBitmaps.get(imageUrl);
				}
			}
			if (mImageCachePref.contains(imageUrl)) {
				Bitmap bitmap = Utils.decodeFromBase64(mImageCachePref.getString(imageUrl, null));
				synchronized (mCachedBitmaps) {
					mCachedBitmaps.put(imageUrl, bitmap);
				}
				return bitmap;
			} else {
				synchronized (mLoading) {
					if (!mLoading.contains(imageUrl)) {
						mLoading.add(imageUrl);
						new AsyncTask<String, Void, Bitmap>() {

							@Override
							protected Bitmap doInBackground(String... params) {
								try {
									Bitmap bitmap = Utils.getBitmapFromUrl(imageUrl, 480, 480);
									if (bitmap != null) {
										synchronized (mImageCachePref) {
											mImageCachePref.edit().putString(imageUrl, Utils.encodeToBase64(bitmap)).commit();
										}
										synchronized (mCachedBitmaps) {
											mCachedBitmaps.put(imageUrl, bitmap);
										}
									}
									return bitmap;
								} catch (Exception e) {
									e.printStackTrace();
								}
								return null;
							}

							protected void onPostExecute(Bitmap result) {
								super.onPostExecute(result);
								synchronized (mLoading) {
									mLoading.remove(imageUrl);
								}
								if (result != null) {
									mGridViewAdatper.notifyDataSetChanged();
								}

							};
						}.execute(imageUrl);
					}
				}
				return mWaiting;
			}
		}

		public class ViewHolder {
			ImageView cover;
			TextView bookName;
			TextView bookUrl;
		}

	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int position, long arg3) {
		SearchBookItem item = mGridViewAdatper.getItem(position);
		Intent intent = createOpenBookIntent(item);
		getActivity().startActivity(intent);
	}
}
